/*
 * File Name:               VirtualJoystick_Fixed.cs
 * 
 * Description:             普通类
 * Author:                  lisiyu <576603306@qq.com>

 * Create Date:             2017/06/03
 */

namespace UnityEngine.UI
{
    using UnityEngine;
    using EventSystems;
    using System.Collections.Generic;

    [AddComponentMenu("UI/VirtualJoystick_Fixed", 70)]
    [DisallowMultipleComponent]
    [RequireComponent(typeof(Graphic))]
    public class VirtualJoystick_Fixed : IVirtualJoystick, IPointerDownHandler, IPointerUpHandler, IDragHandler
    {
        public RectTransform TransFixed;            // 固定节点
        public RectTransform TransMoved;            // 移动节点

        public float MaxDistance = 30f;             // 移动节点与固定节点的最大距离
        private Vector3 m_FixedPos;                 // 固定节点的世界坐标

        private List<Graphic> mChildGraphics;       // 所有图形
        private readonly Color ColorHide = new Color(1, 1, 1, 0.5f);
        private readonly Color ColorShow = new Color(1, 1, 1, 1f);
        void Awake()
        {
            mChildGraphics = new List<Graphic>();
            mChildGraphics.AddRange(TransFixed.GetComponentsInChildren<Graphic>());
            mChildGraphics.AddRange(TransMoved.GetComponentsInChildren<Graphic>());

            showOrHide(false);
        }

        private void Start()
        {
            m_FixedPos = TransFixed.position;
        }

        public void OnDrag(PointerEventData eventData)
        {
            setMovedPos_ByScreen(eventData.position);
        }

        public void OnPointerDown(PointerEventData eventData)
        {
            showOrHide(true);

            setMovedPos_ByScreen(eventData.position);
        }

        public void OnPointerUp(PointerEventData eventData)
        {
            TransMoved.position = m_FixedPos;

            showOrHide(false);

            if (On_JoystickMoveEnd != null)
                On_JoystickMoveEnd();
        }

        private void showOrHide(bool show)
        {
            var color = show ? ColorShow : ColorHide;

            foreach(var tmp in mChildGraphics)
            {
                tmp.color = color;
            }
        }

        private void setMovedPos_ByScreen(Vector2 screenPos)
        {
            if (TransMoved == null) return;

            var retPos = UIManager.Singleton.ScreenToWorldPoint(screenPos, TransMoved.position.z);


            var dir = (retPos - m_FixedPos);
            if (dir.magnitude > MaxDistance)
            {
                dir = (retPos - m_FixedPos).normalized * MaxDistance;
            }

            retPos = m_FixedPos + dir;
            TransMoved.position = retPos;

            if (On_JoystickMove != null)
                On_JoystickMove(dir);
        }
    }
}